<template>
  <el-cascader
    v-model="selectValue"
    :clearable="clearable"
    :disabled="disabled"
    :filterable="filterable"
    :options="list"
    :placeholder="placeholder"
    :readonly="readonly"
    @change="onChange"
  />
</template>
<script>
  import { postRequest } from '@/api/mains'

  export default defineComponent({
    name: 'CommonCascader',
    props: {
      modelValue: {
        type: [Number, String],
        default: '',
      },
      url: {
        type: String,
        default: '',
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      clearable: {
        type: Boolean,
        default: true,
      },
      filterable: {
        type: Boolean,
        default: false,
      },
      readonly: {
        type: Boolean,
        default: false,
      },
      placeholder: {
        type: String,
        default: '',
      },
    },
    emits: { 'update:model-value': null, change: null },
    setup(props, { emit }) {
      const selectValue = ref(props.modelValue)
      const list = ref([])

      const getList = async () => {
        const { url } = props

        //  若传入url则按通过url获取数据
        if (url) {
          const { datas } = await postRequest(url)
          list.value = datas
        }
      }

      getList()

      const onChange = (value) => {
        emit('update:model-value', value)
        emit('change', value)
      }

      watch(
        () => props.modelValue,
        (newVal) => {
          if (newVal != selectValue.value) {
            selectValue.value = newVal
          }
        }
      )

      return {
        selectValue,
        list,
        onChange,
      }
    },
  })
</script>
<style lang="scss"></style>
